﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using PJ.Business;
using Microsoft.Practices.Composite.Events;

namespace PJ.Presentation
{
    public abstract class EntityViewModel : BusinessObjectViewModel, IEntityModel
    {

        protected EntityViewModel()
        {
        }

        protected EntityViewModel(string globalId, IEntityService service)
            : base(globalId, service)
        {
        }

        protected EntityViewModel(IBusinessObject obj, IEntityService service)
            : base(obj, service)
        {
        }

        protected EntityViewModel(IView view, IEventAggregator aggregator, IEntityService service)
            : base(view, aggregator, service)
        {
        }

        /// <summary>
        /// GetValues. Sets the businness object properties using the model property values
        /// </summary>
        /// <param name="businessObject">business object to update</param>
        public override IBusinessObject GetValues()
        {
            if (base.GetValues() == null)
            {
                if (IsStringNull(Id))
                    return null;
            }
            BusinessObject.Id = Id;
            return BusinessObject;
        }
        /// <summary>
        /// SetValues. Sets the model properties using the businessobject property values
        /// </summary>
        /// <param name="businessObject"></param>
        public override void SetValues(IBusinessObject businessObject, bool saveBefore)
        {
            base.SetValues(businessObject, saveBefore);
            if (businessObject == null)
                Id = null;
            else
                Id = BusinessObject.Id;
        }

        public virtual string Id
        {
            get { return (string)ThreadUnsafeGetValue(IdProperty); }
            set { ThreadUnsafeSetValue(IdProperty, value); }
        }

        public static readonly DependencyProperty IdProperty =
            DependencyProperty.Register("Id", typeof(string), typeof(EntityViewModel), new UIPropertyMetadata(""));

        #region Protected

        protected override bool ValuesChanged()
        {
            if (base.ValuesChanged())
                return true;
            else
            {
                if (IsBusinessObjectNull)
                {
                    if (IsStringNull(Id))
                        return false;
                    else
                        return true;
                }
                if (StringEqual(Id, BusinessObject.Id))
                    return false;
                else
                    return true;
            }
        }

        new protected IEntity BusinessObject
        {
            get { return base.BusinessObject as IEntity; }
        }

        #endregion

        #region Field

        #endregion
    }
}
